package com.example.consumer;

import com.example.entity.Order;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class OrderDelay1Consumer {

//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(name = "order.delay1.queue", durable = "true"),
//            exchange = @Exchange(name = "order.delay1.exchange",
//                    type = "x-delayed-message", delayed = "true",
//                    arguments = {@Argument(name = "x-delayed-type", value = "topic")}),
//            key = "order.delay1"
//    ), ackMode = "MANUAL")
@RabbitListener(queues = "order.delay1.queue")
    public void handleOrder(@Payload Order order, Channel channel, Message message) throws IOException {// 注意：不要直接获取 deliveryTag 作为参数
        // 正确地从 Message 对象中获取 deliveryTag
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 业务处理
            log.info("order.delay1.queue处理订单：{}", order);
            processOrder(order);
            // 手动确认消息（deliveryTag：消息唯一标识；multiple：是否批量确认）
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("处理订单失败: {}", order, e);

            // 获取重试次数
            Map<String, Object> headers = message.getMessageProperties().getHeaders();
            Integer retryCount = (Integer) headers.getOrDefault("x-retry-count", 0);
            log.info("当前重试次数：{}", retryCount);
            try {
                // 消息处理失败，根据业务需求决定是否重新入队
                if (retryCount < 3) { // 最大重试3次
                    // 重新入队逻辑
                    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
                    Map<String, Object> newHeaders = new HashMap<>(headers);
                    newHeaders.put("x-retry-count", retryCount + 1);
                    builder.headers(newHeaders);

                    // 重新发布消息
                    channel.basicPublish("order.delay.exchange", "order.delay", builder.build(), message.getBody());
                    // 确认原消息
                    channel.basicAck(deliveryTag, false);
                } else {
                    // 达到最大重试次数，拒绝消息并进入死信队列
                    channel.basicNack(deliveryTag, false, false);
                    log.warn("Message rejected after {} retries: {}", retryCount, order);
                }
            } catch (IOException ioException) {
                log.error("处理消息重试失败", ioException);
                try {
                    // 最后的兜底处理
                        channel.basicNack(deliveryTag, false, false);
                } catch (IOException ex) {
                    log.error("最终确认消息失败", ex);
                }
            }
        }
    }



    /**
     * 处理订单业务逻辑
     * @param order 订单对象
     */
    private void processOrder(Order order) {
        // 模拟订单处理逻辑
        log.info("开始处理订单，订单号：{}", order.getId());

        // 这里添加实际的业务处理逻辑
        // 例如：更新数据库、调用其他服务、发送通知等

        // 模拟处理时间
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("订单处理被中断", e);
        }

        // 模拟偶尔的处理失败
//        if (order.getUserId() != null && order.getUserId().contains("ERROR")) {
//            throw new RuntimeException("模拟订单处理失败");
//        }

        log.info("订单处理完成，订单号：{}", order.getUserId());
    }

}